import re
from django import template
from question.question_type import QUESTION_TYPES

register = template.Library()

@register.inclusion_tag('question.html')
def show_question(question):
    """
    Display a question with its answer.
    If the question text contains an <answer> tag then the answer input will
    replace the <answer> tag in the displayed question text.
    If there is no <answer> tag then the answer input will be placed after the
    question text.
    """
    pattern = re.compile(r'(<answer>)')
    closing_pattern = re.compile(r'(</answer>)')
    question_parts = filter(None, pattern.split(question.question))

    question_type = str(question.question_type)

    final_question = []
    if pattern.search(question.question) is not None:
        for part in question_parts:
            if re.match(pattern, part):
                answer_part = ('answer', 
                        QUESTION_TYPES.get(question_type),
                        QUESTION_TYPES.get(question_type).get_answers(question))
                final_question.append(answer_part)
            else:
                part_parts = filter(None, closing_pattern.split(part))
                print part_parts
                if (len(part_parts) > 1 and part_parts[0] != ''):
                    final_question[-1][2].append(part_parts[0])
                final_question.append(('question', None, part_parts[-1]))
    else:
        final_question.append(('question', None, question_parts[0]))
        final_question.append(('line_break', None, '<br />'))
        final_question.append((('answer'), 
                QUESTION_TYPES.get(question_type), 
                QUESTION_TYPES.get(question_type).get_answers(question)))

    return { 'question': question, 
             'question_parts': final_question,
             'answer_counter': Counter(), }

class Counter:
    counter = 0

    def increment(self):
        self.counter += 1
        return self.counter
